document.addEventListener('DOMContentLoaded', () => {
    const urlInput = document.getElementById('url-input');
    const testCountSelect = document.getElementById('test-count');
    const testButton = document.getElementById('test-button');
    const loadingIndicator = document.getElementById('loading-indicator');
    const resultCards = document.getElementById('result-cards');
    const summaryElement = document.getElementById('summary');
    
    let responseChart = null;
    
    // 初始化Chart.js图表
    function initChart(labels, data) {
        const ctx = document.getElementById('response-chart').getContext('2d');
        
        // 如果已经有图表存在，销毁它
        if (responseChart) {
            responseChart.destroy();
        }
        
        responseChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: '响应时间 (ms)',
                    data: data,
                    backgroundColor: 'rgba(52, 152, 219, 0.2)',
                    borderColor: 'rgba(52, 152, 219, 1)',
                    borderWidth: 3,
                    pointBackgroundColor: 'rgba(52, 152, 219, 1)',
                    pointRadius: 5,
                    tension: 0.1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '响应时间 (毫秒)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '测试次数'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '网页响应时间测试结果',
                        font: {
                            size: 18
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `响应时间: ${context.parsed.y} ms`;
                            }
                        }
                    }
                }
            }
        });
    }
    
    // 创建结果卡片
    function createResultCard(index, time, details) {
        const card = document.createElement('div');
        card.className = 'result-card';
        
        const status = details.status >= 200 && details.status < 300 ? '成功' : '失败';
        const statusColor = details.status >= 200 && details.status < 300 ? '#27ae60' : '#e74c3c';
        
        card.innerHTML = `
            <h3>测试 #${index + 1}</h3>
            <p class="time">${time} ms</p>
            <p>状态: <span style="color: ${statusColor}">${status} (${details.status})</span></p>
            <p>内容大小: ${formatSize(details.size)}</p>
        `;
        
        return card;
    }
    
    // 格式化文件大小
    function formatSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // 生成测试结果摘要
    function createSummary(times, details) {
        const avgTime = (times.reduce((a, b) => a + b, 0) / times.length).toFixed(2);
        const minTime = Math.min(...times).toFixed(2);
        const maxTime = Math.max(...times).toFixed(2);
        
        // 计算标准差
        const mean = times.reduce((a, b) => a + b, 0) / times.length;
        const variance = times.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / times.length;
        const stdDev = Math.sqrt(variance).toFixed(2);
        
        // 生成性能评级
        let rating = '';
        if (avgTime < 100) {
            rating = '极快';
        } else if (avgTime < 300) {
            rating = '快速';
        } else if (avgTime < 1000) {
            rating = '良好';
        } else if (avgTime < 3000) {
            rating = '一般';
        } else {
            rating = '较慢';
        }
        
        const url = urlInput.value;
        const displayUrl = url.length > 40 ? url.substring(0, 40) + '...' : url;
        
        summaryElement.innerHTML = `
            <h2>测试结果摘要</h2>
            <p>测试URL: ${displayUrl}</p>
            <p>测试次数: ${times.length}</p>
            <p>平均响应时间: <span class="highlight">${avgTime} ms</span> (${rating})</p>
            <p>最短响应时间: ${minTime} ms</p>
            <p>最长响应时间: ${maxTime} ms</p>
            <p>响应时间标准差: ${stdDev} ms</p>
            <p>最终状态码: ${details[details.length - 1].status}</p>
        `;
    }
    
    // 使用服务器代理测试网页响应时间
    async function testResponseTime(url, testCount) {
        // 确保URL格式正确
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            url = 'https://' + url;
        }
        
        const times = [];
        const details = [];
        
        // 服务器代理URL
        const proxyBaseUrl = '/test-response';
        
        for (let i = 0; i < testCount; i++) {
            try {
                const startTime = performance.now();
                
                // 通过服务器代理发送请求
                const proxyUrl = `${proxyBaseUrl}?url=${encodeURIComponent(url)}`;
                const response = await fetch(proxyUrl);
                const data = await response.json();
                
                const endTime = performance.now();
                
                // 使用服务器返回的响应时间
                const responseTime = data.responseTime || Math.round(endTime - startTime);
                times.push(responseTime);
                
                // 收集详情
                details.push({
                    status: data.status || 0,
                    size: data.size || 0
                });
                
                // 创建结果卡片
                const card = createResultCard(i, responseTime, details[i]);
                resultCards.appendChild(card);
                
                // 更新图表
                const labels = Array.from({length: i + 1}, (_, index) => `测试 ${index + 1}`);
                initChart(labels, times);
                
            } catch (error) {
                console.error('测试失败:', error);
                
                // 处理错误情况
                times.push(0);
                details.push({
                    status: 0,
                    size: 0
                });
                
                // 创建错误结果卡片
                const card = document.createElement('div');
                card.className = 'result-card';
                card.innerHTML = `
                    <h3>测试 #${i + 1}</h3>
                    <p style="color: #e74c3c">测试失败</p>
                    <p>错误: ${error.message || '无法连接到服务器'}</p>
                `;
                resultCards.appendChild(card);
            }
            
            // 如果不是最后一次测试，等待一小段时间再进行下一次测试
            if (i < testCount - 1) {
                await new Promise(resolve => setTimeout(resolve, 500));
            }
        }
        
        // 生成摘要
        createSummary(times.filter(t => t > 0), details);
    }
    
    // 处理测试按钮点击事件
    testButton.addEventListener('click', async () => {
        const url = urlInput.value.trim();
        const testCount = parseInt(testCountSelect.value);
        
        // 验证输入
        if (!url) {
            alert('请输入有效的URL');
            return;
        }
        
        // 重置界面
        testButton.disabled = true;
        resultCards.innerHTML = '';
        summaryElement.innerHTML = '';
        loadingIndicator.style.display = 'flex';
        
        try {
            // 执行测试
            await testResponseTime(url, testCount);
        } catch (error) {
            console.error('测试过程出错:', error);
            alert('测试过程中出现错误: ' + error.message);
        } finally {
            // 恢复界面
            testButton.disabled = false;
            loadingIndicator.style.display = 'none';
        }
    });
    
    // 输入框回车键触发测试
    urlInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && !testButton.disabled) {
            testButton.click();
        }
    });
}); 